package com.cooperate.fly.controller;


import javax.annotation.Resource;
import javax.servlet.http.HttpSession;


import com.cooperate.fly.bo.*;
import com.cooperate.fly.mapper.*;
import com.cooperate.fly.service.buildDB.BuildCaseService;
import com.cooperate.fly.service.buildDB.BuildSchemaService;
import com.cooperate.fly.service.system.Constant;
import com.cooperate.fly.service.system.QuestionService;
import com.cooperate.fly.service.system.UserGroupService;
import com.cooperate.fly.service.system.UserService;
import com.cooperate.fly.web.*;
import com.google.gson.Gson;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import java.util.*;


@Controller
public class LoginController {

    private static Logger log=Logger.getLogger(LoginController.class);
    @Resource
    private UserService userService;
    @Resource
    private BuildSchemaService buildSchemaService;
    @Resource
    private BuildCaseService buildCaseService;
    @Resource
    private UserMapper usermapper;
    @Resource
    private DataRightMapper dataRightMapper;
    @Resource
    private UserGroupService userGroupService;
    @Resource
    private UserGroupMapper userGroupMapper;
    @Resource
    private SchemaMapper schemaMapper;
    @Resource
    private CaseMapper caseMapper;
    @Resource
    private QuestionService questionService;

    @Resource
    private WebFrontHelper webFrontHelper;

    @Value("#{propertiesReader['schema_designer_role_id']}")
    public int schemaDesignerRoleId;
    @Value("#{propertiesReader['case_designer_role_id']}")
    public int caseDesignerRoleId;
    @Value("#{propertiesReader['root_role_id']}")
    public int rootRoleId;
    @Value("#{propertiesReader['dWriteAuth']}")
    public int writeAuth;

    @RequestMapping(value="/login",method=RequestMethod.GET)
    public String loginPage(HttpSession session,Model model){
        //保存session为了用户关闭页面之后能够自动登录
        User user=(User) session.getAttribute(Constant.USER_SESSION_KEY);
        if(user==null){
            return "login";
        }

        int roleId=user.getRoleId();
        if(roleId==schemaDesignerRoleId){
            List<QuestionWithBLOBs> questionList=questionService.findAll();
            List<QuestionNode> questionNodes=WebFrontHelper.buildQuestionGrid(questionList);
            model.addAttribute("questionJson", new Gson().toJson(questionNodes));
            return "schema-design";
        }
        else if(roleId==caseDesignerRoleId){
            List<Schema> schemas = new ArrayList<Schema>();
            List<Case> cases = new ArrayList<Case>();
            List<DataRight> rights = dataRightMapper.selectByUserId(user.getId(),writeAuth);
            Set<Schema> schemaParent = new HashSet<Schema>();
            for(DataRight right : rights){
                int schemaId = right.getSchemaid();
                Schema schema = schemaMapper.selectByPrimaryKey(schemaId);
                schemas.add(schema);
                Schema parent = schemaMapper.selectByPrimaryKey(schema.getParentId());
                if(parent !=null) {
                    schemaParent.add(parent);
                    Queue<Schema> queue = new LinkedList<Schema>();
                    queue.offer(parent);
                    while (!queue.isEmpty()) {
                        Schema p = schemaMapper.selectByPrimaryKey(queue.poll().getParentId());
                        if(p!=null) {
                            schemaParent.add(p);
                            queue.offer(p);
                        }
                    }
                }
                List<Case> schema_cases = caseMapper.selectAllBySchemaId(schemaId);
                cases.addAll(schema_cases);
            }
            for(Schema schema_parent : schemaParent){
                schemas.add(schema_parent);
            }
//            List<Schema> schemas = schemaMapper.selectAll();
//            List<Case> cases = buildCaseService.getAllCases();
            List<BaseNode> schemaAndCases = new ArrayList<BaseNode>();
            schemaAndCases.addAll(schemas);
            for(Case _case : cases){
                schemaAndCases.add(_case);
            }
            BaseTreeNode root = webFrontHelper.buildCaseTree(schemaAndCases, null);
            List<BaseTreeNode> list = new ArrayList<BaseTreeNode>();
            list.add(root);
            String temp=new Gson().toJson(list);
            model.addAttribute("caseData",temp);
            return "case-design";
        }
        else if(roleId==rootRoleId){
            List<User> userList=userService.findAll();
            List<UserNode> userNodes=WebFrontHelper.buildUserGrid(userList, userGroupMapper);
            model.addAttribute("userJson", new Gson().toJson(userNodes));
            ArrayList<UserGroup> groups=userGroupService.findAll();
            TypeTreeNode groupRoot=webFrontHelper.buildGroupTree(groups);
            model.addAttribute("groupTreeJson",new Gson().toJson(groupRoot.getChildren()));
            model.addAttribute("groupJson",new Gson().toJson(groups));
            return "user-design";
        }
        return "grant-tips";
    }

    @RequestMapping(value="/login",method=RequestMethod.POST)
    @ResponseBody
    public Result login(@RequestParam(value="userName",required=true) String userName,@RequestParam(value="password",required=true)String password,HttpSession session){
        User user=this.userService.loadUserByUserNameAndPassword(userName, password);
        if(user!=null){
            log.info("登录成功：{}"+user);
            session.setAttribute(Constant.USER_SESSION_KEY, user);
            return new Result();
        }else{
            return new Result("用户名密码不匹配");
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        if(session!=null){
            session.invalidate();
        }
        return "redirect:/";
    }

    @RequestMapping("checkSession")
    @ResponseBody
    public Result checkSession(HttpSession session){
        if(session.getAttribute(Constant.USER_SESSION_KEY)!=null){
            return new Result();
        }
        return new Result(false);
    }
}
